package org.clipjoint.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import org.clipjoint.entity.Admin;
import org.clipjoint.service.AdminService;
import org.clipjoint.service.impl.AdminServiceImpl;
import org.clipjoint.vo.JsonResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;

/**
 * @author 陈光耀
 * @date 2021/2/22
 */
@WebServlet("/admin")
public class AdminController extends HttpServlet {

    private AdminService adminService = new AdminServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String method = request.getParameter("method");

        switch (method) {
            case "login":
                login(request, response);
                break;
            case "logout":
                logout(request, response);
                break;
            case "modify":
                modify(request, response);
                break;
            case "info":
                info(request, response);
                break;
        }

    }


    //修改个人信息
    private void info(HttpServletRequest request, HttpServletResponse response) throws IOException {

        HttpSession session = request.getSession();

        // 获取在线用户
        Admin onlineAdmin = (Admin) session.getAttribute("onlineAdmin");
        onlineAdmin.setNickname(request.getParameter("nickname"));
        onlineAdmin.setUsername(request.getParameter("username"));

        // 调用service修改用户信息
        int result = 0;
        try {
            result = adminService.updateInfo(onlineAdmin);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        // 判断修改结果
        if (result == 1) {
            // 重新获取用户信息并保存到session
            session.setAttribute("onlineAdmin", onlineAdmin);
            response.getWriter().print(JsonResult.builder().code(0).msg("修改成功！").build().toJsonString());
        } else {
            response.getWriter().print(JsonResult.builder().code(1).msg("修改失败！").build().toJsonString());
        }
    }


    //修改密码
    private void modify(HttpServletRequest request, HttpServletResponse response) throws IOException {

        HttpSession session = request.getSession();

        // 获取在线用户
        Admin onlineAdmin = (Admin) session.getAttribute("onlineAdmin");
        String password = request.getParameter("password");
        String newPassword = request.getParameter("newPassword");

        // 验证原密码是否正确
        if (!onlineAdmin.getPassword().equals(DigestUtil.md5Hex(password))) {
            response.getWriter().print(JsonResult.builder().code(1).msg("原密码错误！").build().toJsonString());
            return;
        }
        if (onlineAdmin.getPassword().equals(DigestUtil.md5Hex(newPassword))) {
            response.getWriter().print(JsonResult.builder().code(1).msg("新密码和旧密码一致！").build().toJsonString());
            return;
        }

        // 调用service修改用户信息
        int result = 0;
        try {
            result = adminService.updatePassword(onlineAdmin.getId(), DigestUtil.md5Hex(newPassword));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        // 判断修改结果
        if (result == 1) {
            session.removeAttribute("onlineAdmin");
            response.getWriter().print(JsonResult.builder().code(0).msg("修改成功！").build().toJsonString());
        } else {
            response.getWriter().print(JsonResult.builder().code(1).msg("修改失败！").build().toJsonString());
        }

    }

    // 退出登录
    private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {

        HttpSession session = request.getSession();

        // 清除session
        session.removeAttribute("onlineAdmin");

        // 删除浏览器上已有的cookie
        Cookie cookie = new Cookie("onlineAdmin", "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        // 重定向到登录页
        response.sendRedirect(request.getContextPath() + "/admin/login.jsp");
    }

    // 登录方法
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {

        HttpSession session = request.getSession();

        // 获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String captcha = request.getParameter("captcha");
        String rememberMe = request.getParameter("rememberMe");

        // 校验验证码
        if (!captcha.equalsIgnoreCase((String) session.getAttribute("captchaCode"))) {
            response.getWriter().print(JsonResult.builder().code(1).msg("验证码错误！").build().toJsonString());
            return;
        }
        session.removeAttribute("captchaCode");

        // 校验用户名是否存在
        Admin admin = Admin.builder().username(username).build();
        Admin result = null;
        try {
            result = adminService.getByUsername(admin);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if (result == null) {
            response.getWriter().print(JsonResult.builder().code(1).msg("用户名不存在！").build().toJsonString());
            return;
        }

        // 校验用户名和密码是否正确
        if (!DigestUtil.md5Hex(password).equals(result.getPassword())) {
            response.getWriter().print(JsonResult.builder().code(1).msg("密码错误！").build().toJsonString());
            return;
        }

        // 当前用户存入session
        session.setAttribute("onlineAdmin", result);

        // 判断是否7天免登录
        Cookie cookie;
        if ("true".equals(rememberMe)) {
            // 创建cookie保存用户信息
            cookie = new Cookie("onlineAdmin", URLEncoder.encode(JSON.toJSONString(result), "utf-8"));
            cookie.setPath("/");
            cookie.setMaxAge(7 * 24 * 60 * 60);
        } else {
            // 删除浏览器上已有的cookie
            cookie = new Cookie("onlineAdmin", "");
            cookie.setPath("/");
            cookie.setMaxAge(0);
        }
        response.addCookie(cookie);

        response.getWriter().print(JsonResult.builder().code(0).msg("登录成功").build().toJsonString());

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
